<?php

namespace App\Http\Controllers\Admin\Banner;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Services\BannerService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class BannerController extends Controller
{
    /**
     * 获取 banner 位数据
     * @param Request $request
     * @return JsonResponse
     */
    public function bannerList(Request $request): JsonResponse
    {
        $page      = $request->input('page', 1);
        $limit     = $request->input('limit', 1);
        $sortField = $request->input('sort', 'updated_at');
        $orderRule = $request->input('order', 'desc');

        try {
            $data = (new BannerService())->getBannerList($page, $limit, $sortField, $orderRule);
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }

        return result(0, 'ok', $data);
    }

    public function banner(Request $request)
    {

    }

    /**
     * 根据 banner 位 id 获取当前 banner 位下的所有图片
     * @param Request $request
     * @return JsonResponse
     */
    public function bannerItem(Request $request): JsonResponse
    {
        $rule        = [
            "id"      => "required|integer",
        ];
        $input       = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors()->first());
        }

        try {
            $data = (new BannerService())->getBannerItem($input);
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }

        return result(0, 'ok', $data);
    }

    /**
     * 保存 banner 位 (也包括编辑)
     * @param Request $request
     * @return JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        $rule = [
            "user_id"        => "required|integer",
            "name"           => "required|string",
            "imgs"           => "required|array",
            "banner_id"      => "present|nullable|integer",
            "description"    => "present|nullable|string"
        ];
        $input       = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors());
        }

        try {
            (new BannerService())->storeBanner($input);
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }

        return result(0, 'ok', []);
    }
}
